package com.java.basis.thread.n5.singleton;

import java.io.Serializable;

/**
 * @author wangning
 * @create 2022-01-26 15:12
 */
public class Singleton implements Serializable {
	//如果实现了序列化，怎么防止反序列化破坏单例
	private Singleton() {}

	// 在反序列化时，用这个方法返回的对象引用替代readObject新建的引用
	private Object readResolve() {
		return instance;
	}

	private static Singleton instance = null;

	public synchronized static Singleton getInstance() {
		if(instance == null) {
			instance = new Singleton();
		}
		return instance;
	}

	public void print() {}
}

class Singleton01 {
	private Singleton01() {}

	private volatile static Singleton01 instance = null;

	public static Singleton01 getInstance() {
		//这样写再多线程下可能会出现问题，在同步代码块外面可能会进行指令重排序
		//解决方法：给instance加上volatile
		if(instance == null) {
			synchronized (Singleton02.class) {
				if (instance == null) {
					instance = new Singleton01();
				}
			}
		}
		return instance;
	}

	public void print() {}

}

class Singleton02 {
	private Singleton02() {}

	//懒汉式的，使用静态内部类的方式
	private static final class InstanceHolder {
		static final Singleton02 instance = new Singleton02();
	}

	public static Singleton02 getInstance() {
		return InstanceHolder.instance;
	}

	public void print() {}

}
